<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片页 -->
    <el-card class="box-card">
      <!-- 提示信息 -->
      <el-alert title="添加商品信息" type="info" center show-icon>
      </el-alert>
      <!-- 步骤条 -->
      <el-steps :space="250" :active="activeStep - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
      </el-steps>
      <el-form ref="AddGoodFormRef" :model="AddGoodFormData" :rules="addGoodFormRule">
        <el-tabs tab-position="left" v-model="activeStep" :before-leave="tabChange">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="AddGoodFormData.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="AddGoodFormData.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="AddGoodFormData.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="AddGoodFormData.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader v-model="AddGoodFormData.goods_cat" :options="catOptions" :props="catProps"
                @change="cascaderChange"></el-cascader>
            </el-form-item>
            <el-button type="primary" @click="handleNext">下一步</el-button>

          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <div v-if="manyTableData.length == 0">暂无数据</div>
            <el-form-item v-else v-for="(item) in manyTableData" :key="item.id">
              <!-- 感悟：manyTableData里面的每一个项目下面都有着一个attr_vals属性，是一个数组，保存着参数的信息 -->
              <p>{{item.attr_name}}</p>
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox v-for="(item2) in item.attr_vals" :key="item2.attr_id" :label="item2" border>
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-button type="primary" @click="handleNext">下一步</el-button>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <div v-if="onlyTableData.length == 0">暂无数据</div>
            <el-form-item v-else v-for="(item) in onlyTableData" :key="item.attr_id" :label="item.attr_name">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
            <el-button type="primary" @click="handleNext">下一步</el-button>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- 图片的上传 -->
            <el-upload action="http://127.0.0.1:8888/api/private/v1/upload/" :on-preview="handlePreview"
              :on-change="test" :on-success="handleUpload" :on-remove="handleRemove" :file-list="fileList"
              list-type="picture" :headers="headerObj">
              <el-button size="mini" type="info">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>

            <el-button type="primary" @click="handleNext" style="margin-top: 70px;">下一步</el-button>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor ref="myQuillEditor" v-model="AddGoodFormData.goods_introduce" style="height: 400px;"
              :options="editorOptions" class="quillEditor" />
            <el-button type="primary" @click="submitFormData">提交商品信息</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 显示预览图的对话框 -->
    <el-dialog title="预览" :visible.sync="previewDialogVisible" width="80%">
      <img :src="previewURL" alt="商品图片" style="width: 100%">
    </el-dialog>
  </div>
</template>
<style lang='less' scoped>
  .el-breadcrumb {
    margin-bottom: 20px;
  }

  .el-alert {
    height: 50px;

    /deep/ .el-alert__title,
    /deep/ .el-icon-info:before {
      font-size: 20px;
    }
  }

  .el-cascader {
    width: 100%;
  }

  .el-steps {
    margin-top: 30px;
    margin-bottom: 30px;
  }

  /deep/ .el-tabs--left .el-tabs__item.is-left {
    font-size: 16px;
  }

  .el-steps {
    /deep/ .el-step__head.is-process {
      color: #2c72ff;
      border-color: #2c72ff;
    }

    /deep/ .el-step__title.is-process {
      color: #2c72ff;
    }
  }

  .el-button {
    width: 100%;
    height: 50px;
    font-size: 20px;
    font-weight: bold;
  }

  .dynamicParams {
    margin-bottom: 30px;
  }

  p {
    margin-bottom: 0px;
  }

  p:first-child {
    margin-top: 0px;
  }

  /deep/ .el-dialog__header {
    background-color: #66b1ff;

    .el-dialog__title {
      color: #fff;
      font-size: 30px;
      font-weight: bold;
    }

    .el-dialog__close {
      color: #fff;
      font-size: 20px;
    }
  }

  .quillEditor {
    margin-bottom: 80px;
  }

</style>
<script>
  import _ from 'lodash';
  export default {
    data() {
      return {

        AddGoodFormData: {
          // 为了方便测试，模拟了几项数据
          goods_name: '1',
          goods_price: 0,
          goods_weight: 0,
          goods_number: 0,
          goods_cat: [],
          pics: [],
          goods_introduce: '',
        },
        catOptions: [],
        addGoodFormRule: {
          goods_name: [{
            required: true,
            message: '请输入商品名称',
            trigger: 'blur'
          }],
          goods_price: [{
            required: true,
            message: '请输入商品价格',
            trigger: 'blur'
          }],
          goods_weight: [{
            required: true,
            message: '请输入商品重量',
            trigger: 'blur'
          }],
          goods_number: [{
            required: true,
            message: '请输入商品数量',
            trigger: 'blur'
          }],
          goods_cat: [{
            required: true,
            message: '请输入商品分类',
            trigger: 'blur'
          }],
        },
        catOptions: [],
        catProps: {
          expandTrigger: 'hover',
          label: 'cat_name',
          value: 'cat_id',
          children: 'children'
        },
        activeStep: '0',
        checked1: false,
        manyTableData: [],
        onlyTableData: [],
        fileList: [],
        // 上传图片的请求头对象
        headerObj: {
          Authorization: window.sessionStorage.getItem('token')
        },
        previewDialogVisible: false,
        previewURL: '',
        editorOptions: {
          theme: "snow",
          placeholder: "请输入内容",
          modules: {
            toolbar: [
              ["bold", "italic", "underline", "strike"], // 加粗，斜体，下划线，删除线
              //['blockquote', 'code-block'],                      //引用，代码块
              [{
                header: 1
              }, {
                header: 2
              }], // 几级标题
              [{
                list: "ordered"
              }, {
                list: "bullet"
              }], // 有序列表，无序列表
              [{
                script: "sub"
              }, {
                script: "super"
              }], // 下角标，上角标
              [{
                indent: "-1"
              }, {
                indent: "+1"
              }], // 缩进
              //[{ direction: "rtl" }], // 文字输入方向
              [{
                size: ["small", false, "large", "huge"]
              }], // 字体大小
              [{
                header: [1, 2, 3, 4, 5, 6, false]
              }], // 标题
              [{
                color: []
              }, {
                background: []
              }], // 颜色选择
              [{
                font: []
              }], // 字体
              [{
                align: []
              }], // 居中
              ["clean"], //清除样式
              [("link", "image", "video")], //控制能上传的内容
            ],
          },
        },
        goodsInfo: {}
      }
    },
    methods: {
      // 获取所有的1，2，3级分类
      async getClasses() {
        const {
          data: res
        } = await this.$http.get('categories');
        if (res.meta.status == 200) {
          this.catOptions = res.data;
        } else {
          this.$message.error(res.meta.msg);
        }
      },
      handleNext() {
        this.$refs.AddGoodFormRef.validate((valid) => {
          if (valid) {
            if (this.AddGoodFormData.goods_cat.length == 3) {
              this.activeStep++;
              this.activeStep = this.activeStep + '';
            }
          }
        });
      },
      tabChange(nextTagName, leaveTagName) {
        this.$refs.AddGoodFormRef.validate();
        if (this.AddGoodFormData.goods_cat.length != 3) {
          return false;
        }
      },
      //获取参数或者属性
      async getParamsData(sel) {
        //   判断是否为3级选项
        if (this.AddGoodFormData.goods_cat.length == 3) {
          const {
            data: response
          } = await this.$http.get(
            `categories/${this.AddGoodFormData.goods_cat[this.AddGoodFormData.goods_cat.length - 1]}/attributes`, {
              params: {
                sel: sel
              }
            });
          if (response.meta.status == 200) {
            if (sel == 'many') {
              response.data.forEach(element => {
                if (element.attr_vals == '') {
                  element.attr_vals = [];

                } else {
                  element.attr_vals = element.attr_vals.split(' ');
                }
              });
              this.manyTableData = response.data;
              //   console.log(this.manyTableData);

            } else {
              this.onlyTableData = response.data;
              //   console.log(this.onlyTableData);
            }
          } else {
            console.log(response.meta.msg);


          }
        } else {
          this.manyTableData = [];
          this.onlyTableData = [];
        }
      },
      //   当选完分类之后，立即获取参数
      cascaderChange() {
        this.getParamsData('many');
        this.getParamsData('only');
        console.log(this.manyTableData);
        console.log(this.onlyTableData);
      },
      handlePreview(file) {
        this.previewDialogVisible = true;
        if (this.$route.query.id) {
          this.previewURL = file.url
        } else {
          this.previewURL = file.response.data.url;
        }
      },
      handleRemove(file, fileList) {
        this.AddGoodFormData.pics = fileList;
      },
      handleUpload(file) {
        this.AddGoodFormData.pics.push(file.data.tmp_path);
      },
      //   提交商品信息
      async submitFormData() {
        const addForm = _.cloneDeep(this.AddGoodFormData);
        const PICS = [];
        addForm.goods_cat = addForm.goods_cat.join(',');
        // 处理pics参数
        addForm.pics.forEach(element => {
          PICS.push({
            'pic': element
          });
        });
        addForm.pics = PICS;
        //   处理attrs参数
        addForm.attrs = []
        this.onlyTableData.forEach(element => {
          addForm.attrs.push({
            attr_id: element.attr_id,
            attr_value: element.attr_vals
          })
        });
        this.manyTableData.forEach(element => {
          const vals = element.attr_vals.join(',');
          addForm.attrs.push({
            attr_id: element.attr_id,
            attr_value: vals
          })
        });
        // 判断是新建还是编辑商品信息
        if (this.$route.query.id) {
          const pics = addForm.pics;
          addForm.pics = [];
          pics.forEach(element => {
            addForm.pics.push({
              pic: element.pic.pics_big,
            })
          });
          console.log(addForm);
          const {
            data: response
          } = await this.$http.put(`/goods/${addForm.goods_id}`, addForm);
          if (response.meta.status == 200) {
            this.$message.success(response.meta.msg);
            this.$router.push('/goods');
          } else {
            this.$message.error(response.meta.msg);
          }
        } else {
          const {
            data: response
          } = await this.$http.post('/goods', addForm);
          if (response.meta.status == 201) {
            this.$message.success(response.meta.msg);
            this.$router.push('/goods');
          } else {
            this.$message.error(response.meta.msg);
          }
        }
      },
      test() {
        // console.log(this.AddGoodFormData.pics);
        // console.log(this.fileList);
      },
      async getGoodsInfoById(id) {
        const {
          data: response
        } = await this.$http.get(`goods/${id}`);
        if (response.meta.status != 200) {
          this.$message.error(response.meta.msg);
          return;
        }

        response.data.goods_cat = response.data.goods_cat.split(',');
        response.data.goods_cat.forEach((value, index) => {
          response.data.goods_cat[index] = value - 0;
        });
        response.data.attrs.forEach((value) => {
          if (value.attr_sel == 'many') {
            value.attr_vals = value.attr_vals.split(',');
            this.manyTableData.push(value);
          } else {
            this.onlyTableData.push(value);
          }
        });
        // 将每张照片的url和名字往这个里面放就可
        // this.fileList = [{
        //   name: 'test',
        //   url: "http://127.0.0.1:8888/uploads/goodspics/mid_042644efec5cd015b37602e7009cc1f3.jpg"
        // }];
        this.AddGoodFormData = response.data;
        this.AddGoodFormData.pics.forEach(element => {
          this.fileList.push({
            name: element.pics_big.split('/')[3],
            url: element.pics_big_url
          })
        });
      }
    },
    created() {
      this.getClasses();
      if (this.$route.query.id) {
        this.getGoodsInfoById(this.$route.query.id);
      }
    }
  }

</script>
